package main

import "sync"

type SimpleGenericCache[K Ordered, V any] struct { // 使用 Ordered
	cache map[K]V
	mu    sync.RWMutex
}

/*简单缓存------------------*/

//对象初始化
func NewSimpleGenericCache[K Ordered, V any]() (*SimpleGenericCache[K, V], error) {
	if err := checkGoVersionCanUseGenerics(); err != nil {
		return nil, err
	}
	return &SimpleGenericCache[K, V]{
		cache: make(map[K]V),
	}, nil
}

// 设置缓存项
func (c *SimpleGenericCache[K, V]) Set(key K, value V) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.cache[key] = value
}

// 获取缓存项
func (c *SimpleGenericCache[K, V]) Get(key K) (V, bool) {
	c.mu.RLock()
	defer c.mu.RUnlock()
	value, ok := c.cache[key]
	return value, ok
}

// 删除某个Key
func (c *SimpleGenericCache[K, V]) Del(key K) {
	c.mu.Lock()
	defer c.mu.Unlock()
	delete(c.cache, key)
}

// ShowAllKey 获取所有缓存key
func (c *SimpleGenericCache[K, V]) ShowAllKey() []K {
	keys := make([]K, 0)
	c.mu.RLock()
	defer c.mu.RUnlock()
	for key := range c.cache {
		keys = append(keys, key)
	}
	return keys
}

func (c *SimpleGenericCache[K, V]) UnSafeRlock() {
	c.mu.RLock()
}
func (c *SimpleGenericCache[K, V]) UnSafeRUnlock() {
	c.mu.RUnlock()
}

func (c *SimpleGenericCache[K, V]) UnSafeLock() {
	c.mu.Lock()
}
func (c *SimpleGenericCache[K, V]) UnSafeUnLock() {
	c.mu.Unlock()
}

func (c *SimpleGenericCache[K, V]) UnSafeGet(key K) (V, bool) {
	value, ok := c.cache[key]
	return value, ok
}
func (c *SimpleGenericCache[K, V]) UnSafeSet(key K, value V) {
	c.cache[key] = value
}
